package com.broada.apm.logic;

import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.base.BaseLogic;
import com.broada.apm.es.indices.support.PerfIndicesBuilder;
import com.broada.apm.indicator.api.common.ApmDataIndicatorException;
import com.broada.apm.utils.ConfigureProperties;
import com.broada.apm.utils.EsClientUtil;
import com.broada.apm.utils.ExceptionUtils;
import com.broada.apm.utils.RestClientUtil;

/**
 * 历史数据管理类
 * 
 * @author louyi Create By Feb 5, 2015 2:55:41 PM
 */
public class ClearHistoryPerfData extends BaseLogic {
	private Logger log = LoggerFactory.getLogger(ClearHistoryPerfData.class);
	private PerfIndicesBuilder builder = PerfIndicesBuilder.getInstance();
	private String optimize = EsClientUtil.getEsHttpUrl() + "/_optimize";
	private String non_trade_perf_keep_day = ConfigureProperties.getString("non.trade.perf.keep.day", "7");
	private String perf_data_build_rule = ConfigureProperties.getString("perf.data.build.rule", "d");

	/**
	 * 清除历史性能数据
	 * 
	 * @throws Exception
	 */
	public void clear() {
		try {
			clearHistoryPerfIndex();
			clearTradePerf();
			apmIndexOptimize();
		} catch (ApmDataIndicatorException e) {
			ExceptionUtils.error(log, "清除性能数据发生错误...", e);
		}
	}

	private void clearHistoryPerfIndex() throws ApmDataIndicatorException {
		// 获取保留数据的时间...
		//TODO
//		ConfigItem item = queryService.queryObject(Scope.APMSYSTEM_SETTINGS, ConfigItem.class,
//				SettingMapConstants.SETTINGSMAP.get("history.cleantime"));
//		int times = Integer.valueOf(item.getValue());
//		log.info("开始清除历史性能数据...");
//		builder.clearPerfIndex(times);
//		log.info("清除历史性能数据结束...");
	}

	/**
	 * 优化索引
	 */
	private void apmIndexOptimize() {
		log.info("开始优化索引性能...");
		RestClientUtil.doAction("post", optimize, "");
		log.info("优化索引性能结束...");
	}

	/**
	 * 非关键交易性能管理 清除day之前的性能数据
	 * 
	 * @param days
	 * @return
	 * @throws ApmDataIndicatorException
	 */
	public void clearTradePerf() throws ApmDataIndicatorException {
		String[] delIndex = null;
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - Integer.valueOf(non_trade_perf_keep_day));

		// 查询所有交易索引
		String[] indexs = builder.searchIndex("apm_perf_a*_r_y*");
		log.info("开始清除非关键交易性能...");
		if (ArrayUtils.isNotEmpty(indexs)) {
			if ("d".equals(perf_data_build_rule.toLowerCase())) {
				// 获取需要保留的开始年份和月份
				int destYear = calendar.get(Calendar.YEAR);
				int destMonth = calendar.get(Calendar.MONTH) + 1;
				int destDay = calendar.get(Calendar.DAY_OF_MONTH);
				for (String index : indexs) {
					int y = index.indexOf("_y");
					int m = index.indexOf("_m");
					int d = index.lastIndexOf("_d");
					if (d < m)
						continue;
					int srcYear = Integer.valueOf(index.substring(y + 2, m));
					int srcMonth = Integer.valueOf(index.substring(m + 2, d));
					int srcDay = Integer.valueOf(index.substring(d + 2));
					if (srcYear < destYear || (srcYear == destYear && srcMonth < destMonth)
							|| (srcYear == destYear && srcMonth == destMonth && srcDay < destDay))
						delIndex = (String[]) ArrayUtils.add(delIndex, index);
				}
				PerfIndicesBuilder.getInstance().deleteIndex(delIndex); // 清除es库中索引
				PerfIndicesBuilder.getInstance().deleteFromCache(delIndex); // 清除缓存中的索引
			} else {
				perService.clearPerf(indexs, builder.TYPE, calendar.getTimeInMillis(), null);
				PerfIndicesBuilder.getInstance().deleteFromCache(indexs); // 清除缓存中的索引
			}
		}
		log.info("清除非关键交易性能结束...");
	}

}
